package com.yiboshi.rehrs.helper;

import com.alibaba.fastjson.JSONObject;
import com.yiboshi.rehrs.param.ZhongReq;
import com.yiboshi.rehrs.util.*;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Data
@Builder
@Slf4j
public class ZhongHeaderHelper {

    List<String> domainList;

    String aesKeyStr;

    String aesIvStr;

    String signStr;

    Map<String,String> pathTypeMap;




    public static ZhongHeaderHelper getDefaulCpsConfig() {
        return ZhongHeaderHelper.builder()
                .domainList(Arrays.asList("http://121.62.30.160:2025/api/user/1000/android/5.3.7/"))
                .aesIvStr("b848d08061100668")
                .aesKeyStr("41212a6e7ae3f081106ab92fd616c3b5")
                .signStr("0sRw1sJsHYacCyDBOA03HOEZ6Jymy0Yi")
                .build();
    }

    public static void mainThread(String[] args) throws Exception{
        // 创建固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(1);
        CountDownLatch latch = new CountDownLatch(10);

        // 启动多个线程执行test()方法
        for (int i = 0; i < 10; i++) {
            final int threadNum = i + 1;
            executor.submit(() -> {
                try {
                    System.out.println("线程" + threadNum + "开始执行test()");
                    test();
                    System.out.println("线程" + threadNum + "执行完成");
                } catch (Exception e) {
                    System.err.println("线程" + threadNum + "执行出错: " + e.getMessage());
                    e.printStackTrace();
                } finally {
                    latch.countDown();
                }
            });
        }

        try {
            // 等待所有线程执行完成
            latch.await();
            System.out.println("所有线程执行完毕");
        } catch (InterruptedException e) {
            System.err.println("主线程等待被中断: " + e.getMessage());
            Thread.currentThread().interrupt();
        } finally {
            executor.shutdown();
        }
    }

    public static void main(String[] args) throws Exception {
        test();
    }


    public static void test() throws Exception {
        //下段查询
        String api = "token=%s&type=findwaybillnoinfoone&pda_user_token=%s&imei=869296041015581&dev=&time=%d";
        ZhongReq zhongReq = new ZhongReq();
        String token = "db5b44026568c5f8d35b7489fe57a2e2";
        String ivStr = "b848d08061100668";
        byte[] aesKeyStrBytes = "41212a6e7ae3f081106ab92fd616c3b5".getBytes();
        zhongReq.setOriginData(String.format(api,token, MD5.encode(token),System.currentTimeMillis()));
        ZhongHeaderHelper defaulZhongHeaderHelper = getDefaulCpsConfig();
        String encrypt = MyAESUtil.encrypt(zhongReq.getOriginData(), aesKeyStrBytes,
                ivStr);
        String sign = MyAESUtil.sign(zhongReq.getOriginData(), "0sRw1sJsHYacCyDBOA03HOEZ6Jymy0Yi");
        zhongReq.setData(encrypt);
        zhongReq.setSign(sign);
        JSONObject end = JSONBuilder.start()
                .put("data", encrypt).put("sign", sign).end();
        OkHttpUtil post = new OkHttpUtil().url("http://121.62.30.160:2025/api/user/1000/android/5.3.7/vip")
                .retryCount(0)
                .post(end.toJSONString());
        String executeRes = post.execute();
        //解密返回关键参数

        JSONObject jsonObject = JSONObject.parseObject(executeRes);
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        String dataStr = jsonObject.getString("data");
        String decryptAES = MyAESUtil.decryptAES(dataStr,
                aesKeyStrBytes, ivStr);

        JSONObject jsonObject1 = JSONObject.parseObject(decryptAES);
        JSONObject header = jsonObject1.getJSONObject("headers");
        JSONObject qi5uxeelJSON = jsonObject1.getJSONObject("qi5uxeel");

        String cpsMagic = qi5uxeelJSON.getString("cpsMagic");
        String qi5uxeel = qi5uxeelJSON.getString("qi5uxeel");
        log.info("qi5uxeel:{}",qi5uxeel);

        Map<String,String> headers = new HashMap<>();



        JSONObject jsonObject2 = JSONObject.parseObject("{\"pda_user_token\":\"\",\"jdpt_req_time\":\"\",\"jdpt_sign\":\"\",\"qi5uxeel\":\"\",\"cps-magic\":\"\",\"person_no\":\"\",\"pda_id\":\"\",\"dlv_equipment_type\":\"Newland\",\"algorithm_flag\":\"B\",\"pda_type\":\"A\",\"pda_sys\":\"Android\",\"version_name\":\"1.4.6\",\"host\":\"211.156.197.65\",\"user-agent\":\"Dalvik/2.1.0 (Linux; U; Android 9; Build/PQ3A.190801.002)\",\"connection\":\"Keep-Alive\",\"pda_sys_version\":\"10\",\"pda_version\":\"245\",\"safe_id\":\"ISRS\",\"cookie\":\"CORAL_GRAYLEVEL=0\",\"content-type\":\"application/json; charset=utf-8\"}");
        jsonObject2.entrySet().forEach(entry -> {
            headers.put(entry.getKey(), entry.getValue().toString());
        });
        headers.put("cps-magic", cpsMagic);
        headers.put("qi5uxeel", qi5uxeel);

        Thread.sleep(100000);

        String person_no = "2153011500166";
        String pda_user_token = "b902c08c001f430a8fb06c4678563bd9";
        headers.put("pda_user_token",pda_user_token);
        headers.put("person_no",person_no);
        headers.put("pda_id","869296041015581");
        headers.put("pda_version","1.4.14a");
        String Jdpt_req_time = String.valueOf(System.currentTimeMillis()+AperStringUtils.randomNum(1000));
        String Jdpt_sign = SHA256Util.Jdpt_sign(Jdpt_req_time, pda_user_token,person_no);
        headers.put("jdpt_req_time",Jdpt_req_time);
        headers.put("jdpt_sign",Jdpt_sign);

        String apiUrl = "http://211.156.197.65/delivery-app/p/pdasetroadsegone/findwaybillnoinfoone";


        OkHttpUtil okHttpUtil = new OkHttpUtil().url(apiUrl)
                .retryCount(0)
                .post("{  \"waybillNo\": \"1357206724930\",  \"alarmFlag\": \"0\",  \"roadCode\": \"24\",  \"roadName\": \"24段\",  \"tongqian\": \"\",  \"acquisitionMethod\": \"扫描识别\",  \"signFlag\": \"41e368a3-2b3d-4ee5-83ae-d4f203c4dee3****JDPT\"}")
                .headers(headers);
        String execute = okHttpUtil.execute();
        System.out.println("第一次休眠10s"+execute);


        Thread.sleep(2000);
        Jdpt_req_time = String.valueOf(System.currentTimeMillis()+AperStringUtils.randomNum(1000));
        Jdpt_sign = SHA256Util.Jdpt_sign(Jdpt_req_time, pda_user_token,person_no);
        headers.put("jdpt_req_time",Jdpt_req_time);
        headers.put("jdpt_sign",Jdpt_sign);
        okHttpUtil = new OkHttpUtil().url(apiUrl)
                .retryCount(0)
                .post("{  \"waybillNo\": \"9809012406251\",  \"alarmFlag\": \"0\",  \"roadCode\": \"24\",  \"roadName\": \"24段\",  \"tongqian\": \"\",  \"acquisitionMethod\": \"扫描识别\",  \"signFlag\": \"41e368a3-2b3d-4ee5-83ae-d4f203c4dee3****JDPT\"}")
                .headers(headers);
        try {
            execute = okHttpUtil.execute();
        } catch (Exception e) {
           System.err.println("第2次休眠2s error"+e.getMessage());
        }
        System.out.println("第2次休眠2s"+execute);

        Thread.sleep(2000);
        Jdpt_req_time = String.valueOf(System.currentTimeMillis()+AperStringUtils.randomNum(1000));
        Jdpt_sign = SHA256Util.Jdpt_sign(Jdpt_req_time, pda_user_token,person_no);
        headers.put("jdpt_req_time",Jdpt_req_time);
        headers.put("jdpt_sign",Jdpt_sign);
        okHttpUtil = new OkHttpUtil().url(apiUrl)
                .retryCount(0)
                .post("{  \"waybillNo\": \"9809012406250\",  \"alarmFlag\": \"0\",  \"roadCode\": \"24\",  \"roadName\": \"24段\",  \"tongqian\": \"\",  \"acquisitionMethod\": \"扫描识别\",  \"signFlag\": \"41e368a3-2b3d-4ee5-83ae-d4f203c4dee3****JDPT\"}")
                .headers(headers);
        try {
            execute = okHttpUtil.execute();
        } catch (Exception e) {
            System.err.println("第3次休眠2s error"+e.getMessage());
        }
        System.out.println("第3次休眠2s"+execute);

    }

}
